from PyQt5.QtWidgets import (QMainWindow, QGroupBox, QVBoxLayout, QHBoxLayout,
                             QListWidget, QPushButton, QLabel, QFormLayout,
                             QDoubleSpinBox, QProgressBar, QMessageBox)
from PyQt5.QtCore import Qt
from config.settings import *


class SheepDetectorUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.init_signals()

    def init_ui(self):
        """初始化界面布局"""
        self.setWindowTitle(WINDOW_TITLE)
        self.setGeometry(*WINDOW_GEOMETRY)

        # 左侧控制面板
        control_panel = QVBoxLayout()
        control_panel.addWidget(self.create_model_group())
        control_panel.addWidget(self.create_image_group())
        control_panel.addWidget(self.create_params_group())
        control_panel.addWidget(self.create_detect_button())
        control_panel.addWidget(self.create_progress_bar())

        # 右侧显示面板
        display_panel = QVBoxLayout()
        display_panel.addWidget(self.create_image_display())
        display_panel.addWidget(self.create_results_group())

        # 主布局
        main_layout = QHBoxLayout()
        main_layout.addLayout(control_panel, 1)
        main_layout.addLayout(display_panel, 3)

        central_widget = QWidget()
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)

    def create_model_group(self):
        """创建模型设置分组"""
        group = QGroupBox("模型设置")
        layout = QVBoxLayout()
        self.model_label = QLabel("未选择模型")
        self.load_btn = QPushButton("加载模型")
        layout.addWidget(self.model_label)
        layout.addWidget(self.load_btn)
        group.setLayout(layout)
        return group

    def create_image_group(self):
        """创建图片管理分组"""
        group = QGroupBox("图片管理")
        layout = QVBoxLayout()
        self.image_list = QListWidget()
        btn_layout = QHBoxLayout()
        self.import_btn = QPushButton("导入图片")
        self.clear_btn = QPushButton("清空列表")
        btn_layout.addWidget(self.import_btn)
        btn_layout.addWidget(self.clear_btn)
        layout.addWidget(self.image_list)
        layout.addLayout(btn_layout)
        group.setLayout(layout)
        return group

    def create_params_group(self):
        """创建参数设置分组"""
        group = QGroupBox("检测参数")
        layout = QFormLayout()
        self.conf_spin = QDoubleSpinBox()
        self.iou_spin = QDoubleSpinBox()
        self.conf_spin.setRange(*CONF_RANGE)
        self.iou_spin.setRange(*IOU_RANGE)
        self.conf_spin.setValue(DEFAULT_CONF_THRESHOLD)
        self.iou_spin.setValue(DEFAULT_IOU_THRESHOLD)
        self.conf_spin.setSingleStep(STEP)
        self.iou_spin.setSingleStep(STEP)
        layout.addRow("置信度阈值:", self.conf_spin)
        layout.addRow("IOU阈值:", self.iou_spin)
        group.setLayout(layout)
        return group

    def create_detect_button(self):
        """创建检测按钮"""
        btn = QPushButton("开始检测")
        btn.setEnabled(False)
        return btn

    def create_progress_bar(self):
        """创建进度条"""
        bar = QProgressBar()
        bar.setTextVisible(True)
        bar.setRange(0, 100)
        return bar

    def create_image_display(self):
        """创建图片显示区域"""
        label = QLabel("请导入图片并选择一张进行检测")
        label.setAlignment(Qt.AlignCenter)
        label.setMinimumSize(*IMAGE_DISPLAY_SIZE)
        label.setStyleSheet("border: 1px solid #ccc;")
        return label

    def create_results_group(self):
        """创建结果显示分组"""
        group = QGroupBox("检测结果")
        layout = QFormLayout()
        self.count_label = QLabel("羊数量: --")
        self.conf_min_label = QLabel("最小置信度: --")
        self.conf_max_label = QLabel("最大置信度: --")
        self.conf_avg_label = QLabel("平均置信度: --")
        layout.addRow(self.count_label)
        layout.addRow(self.conf_min_label)
        layout.addRow(self.conf_max_label)
        layout.addRow(self.conf_avg_label)
        group.setLayout(layout)
        return group

    def init_signals(self):
        """初始化信号连接"""
        self.load_btn.clicked.connect(self.on_load_model)
        self.import_btn.clicked.connect(self.on_import_images)
        self.clear_btn.clicked.connect(self.on_clear_images)
        self.image_list.itemClicked.connect(self.on_image_selected)

    # 界面交互方法（信号处理函数）
    def show_model_path(self, path):
        self.model_label.setText(path.split("/")[-1])

    def show_image_list(self, images):
        self.image_list.clear()
        self.image_list.addItems([img.split("/")[-1] for img in images])

    def show_detection_result(self, image, count, metrics):
        # 显示图片逻辑（需调用image_utils中的方法）
        pass

    # 错误提示方法
    def show_warning(self, message):
        QMessageBox.warning(self, "警告", message)